<?php

namespace App\Http\Controllers;

use App\Services\LotteryService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

/**
 * 抽奖控制器
 */
class LotteryController extends Controller
{
    private $lotteryService;

    public function __construct(LotteryService $lotteryService)
    {
        $this->lotteryService = $lotteryService;
    }

    /**
     * 抽奖接口
     * 
     * 处理流程：
     * 1. 生成随机用户ID（测试用）
     * 2. 调用抽奖服务
     * 3. 处理抽奖结果
     * 4. 异常处理和日志记录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function draw(Request $request): JsonResponse
    {
        // 生成随机用户ID（实际项目中应该从登录态获取）
        $userId = mt_rand(1000000, 9999999);
        
        Log::info('收到抽奖请求', [
            'user_id' => $userId,
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent()
        ]);

        try {
            // 调用抽奖服务
            $result = $this->lotteryService->draw($userId);

            // 处理抽奖结果
            if ($result === null) {
                Log::info('抽奖结果：未中奖', [
                    'user_id' => $userId
                ]);
                
                return response()->json([
                    'code' => 0,
                    'message' => '很遗憾，未中奖'
                ]);
            }

            Log::info('抽奖结果：中奖', [
                'user_id' => $userId,
                'prize_info' => $result
            ]);

            return response()->json([
                'code' => 1,
                'message' => '恭喜中奖',
                'data' => $result
            ]);
            
        } catch (\InvalidArgumentException $e) {
            // 参数错误
            Log::warning('抽奖参数错误', [
                'user_id' => $userId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'code' => -1,
                'message' => '参数错误：' . $e->getMessage()
            ], 400);
            
        } catch (\RuntimeException $e) {
            // 业务逻辑错误
            Log::error('抽奖业务错误', [
                'user_id' => $userId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'code' => -1,
                'message' => '抽奖失败：' . $e->getMessage()
            ], 400);
            
        } catch (\Exception $e) {
            // 系统错误
            Log::error('抽奖系统错误', [
                'user_id' => $userId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'code' => -1,
                'message' => '系统繁忙，请稍后重试'
            ], 500);
        }
    }
} 